package com.eightbears.beboy.ui.user.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShopCommentAdapter;
import com.eightbears.beboy.adapter.ShopManagersAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.banner.LocalImageHolderView;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.popupwindow.BottomSelectionPopup;
import com.eightbears.beboy.base.view.popupwindow.HongBaoPopup;
import com.eightbears.beboy.entity.FollowShopEntity;
import com.eightbears.beboy.entity.ShopCommentEntity;
import com.eightbears.beboy.entity.ShopDetailEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.merchant.activity.ReservationShopActivity;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_TRUE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_FOUCE_SHOP;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPS_DETAILS;
import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;
import static com.eightbears.beboy.ui.user.fragment.FindFragment.PARAMS_SHOP_ID;

public class ShopDetailActivity extends BaseActivity implements OnItemClickListener {

    public static final String PARAMS_MANAGE_INFO = "manageInfo";
    public static final String PARAMS_SHOPID = "shopdetail";
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_right_img_btn)
    TextView tv_right_img_btn;
    @BindView(R.id.iv_hongbao)
    ImageView iv_hongbao;

    // 头部布局
    private MapView mapView;
    private AMap aMap;
    private TextView tv_address;
    private RelativeLayout rl_shop_address;
    private TextView tv_shop_name;
    private RatingBar rb_start;
    private TextView tv_count;
    private ConvenientBanner convenientBanner;
    private RelativeLayout rl_convenientBanner;
    private RelativeLayout rl_contact;
    private TextView tv_avg_price;
    private Button btn_apply_manager;
    private RecyclerView rv_manager;
    private TextView tv_comment_count;
    private LinearLayout ll_all_comment;
    private LinearLayout ll_manager;
    private TextView tv_shop_detail;

    private Bundle savedInstanceState;
    private String shopId;
    private LatLng mLatLng;
    private String[] phones;
    private ShopDetailEntity shopDetailEntity;
    private ShopCommentAdapter mShopCommentAdapter;
    private RelativeLayout mRl_technician;
    private TextView mTv_gril;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.savedInstanceState = savedInstanceState;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        shopId = getIntent().getStringExtra(PARAMS_SHOP_ID);
        tv_title.setText(getText(R.string.text_shop_detail));
    }

    @Override
    protected void initData() {
        initAdapter();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    /**
     * 初始化地图属性
     */
    private void setUpMap() {
        UiSettings settings = aMap.getUiSettings();
        settings.setCompassEnabled(true);
        settings.setScaleControlsEnabled(true);
        settings.setZoomControlsEnabled(false);//设置地图不能移动
        settings.setScrollGesturesEnabled(false);
        settings.setRotateGesturesEnabled(false);
        settings.setTiltGesturesEnabled(false);
    }

    private void initAdapter() {
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        mShopCommentAdapter = new ShopCommentAdapter();
        mShopCommentAdapter.openLoadAnimation();
        mShopCommentAdapter.addHeaderView(getHeadView());
        mShopCommentAdapter.addFooterView(getFootView());
        rv_list.setAdapter(mShopCommentAdapter);
        mShopCommentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ShopCommentEntity.ShopComment shopComment =
                        (ShopCommentEntity.ShopComment) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.iv_user_head:
                        startLocalActivity(ShopDetailActivity.this, UserInfoActivity.class,
                                PARAMS_USER_INFO, shopComment.getUser_id());
                        break;
                }
            }
        });
        getShopComment();
    }

    private void getShopInfo() {
        String url = URL_SHOPS_DETAILS + shopId;
        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                shopDetailEntity = GsonUtil.fromJson(response, ShopDetailEntity.class);
                if (shopDetailEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    initHeadViewData();
                    initHeadViewEvent();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopDetailActivity.this, status_error);
            }
        });
    }

    private void getShopComment() {
        String url = URL_SHOPS_DETAILS + shopId + "/comments";
        OkHttpUtils.get().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", "1")
                .addParams("size", "3")
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                ShopCommentEntity shopCommentEntity = GsonUtil.fromJson(response, ShopCommentEntity.class);
                if (shopCommentEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    mShopCommentAdapter.setNewData(shopCommentEntity.getData().getList());
                    if (null != shopCommentEntity.getData().getList()
                            && shopCommentEntity.getData().getList().size() >= 3) {
                        ll_all_comment.setVisibility(View.VISIBLE);
                    }
                    initMap();
                    mapView.onCreate(savedInstanceState);
                    getShopInfo();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopDetailActivity.this, status_error);
            }

        });
    }

    private void executeFollow() {
        String url = URL_FOUCE_SHOP + "/" + shopId + "/fav";
        OkHttpUtils.post().url(url)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                FollowShopEntity followShopEntity = GsonUtil.fromJson(response, FollowShopEntity.class);
                if (followShopEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    if (followShopEntity.getData().getStatus().equals(STATUS_TRUE)) {
                        ShowToast.showShortToast(getString(R.string.text_aread_follow));
                        tv_right_img_btn.setSelected(true);
                    } else {
                        ShowToast.showShortToast(getString(R.string.text_cancel_follow));
                        tv_right_img_btn.setSelected(false);
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopDetailActivity.this, status_error);
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.tv_right_img_btn)
    void followShop() {
        executeFollow();
    }

    @OnClick(R.id.iv_hongbao)
    void getHongBao() {

        HongBaoPopup hongBaoPopup = new HongBaoPopup(this, shopId);
        hongBaoPopup.showPopupWindow();
    }

    private View getHeadView() {
        View view = getLayoutInflater().inflate(R.layout.head_shop_detail, null);
        mapView = (MapView) view.findViewById(R.id.map_top);
        tv_address = (TextView) view.findViewById(R.id.tv_address);
        tv_shop_name = (TextView) view.findViewById(R.id.tv_shop_name);
        rl_shop_address = (RelativeLayout) view.findViewById(R.id.rl_shop_address);
        rb_start = (RatingBar) view.findViewById(R.id.rb_start);
        tv_count = (TextView) view.findViewById(R.id.tv_count);
        convenientBanner = (ConvenientBanner) view.findViewById(R.id.convenientBanner);
        rl_convenientBanner = (RelativeLayout) view.findViewById(R.id.rl_convenientBanner);
        rl_contact = (RelativeLayout) view.findViewById(R.id.rl_contact);
        tv_avg_price = (TextView) view.findViewById(R.id.tv_avg_price);
        btn_apply_manager = (Button) view.findViewById(R.id.btn_apply_manager);
        rv_manager = (RecyclerView) view.findViewById(R.id.rv_manager);
        tv_comment_count = (TextView) view.findViewById(R.id.tv_comment_count);
        tv_shop_detail = (TextView) view.findViewById(R.id.tv_shop_detail);
        ll_manager = (LinearLayout) view.findViewById(R.id.ll_manager);
        mRl_technician = (RelativeLayout) view.findViewById(R.id.rl_technician);
        mTv_gril = (TextView) view.findViewById(R.id.tv_gril);
        return view;
    }

    private View getFootView() {
        View view = getLayoutInflater().inflate(R.layout.view_foot_all_comment, null);
        ll_all_comment = (LinearLayout) view.findViewById(R.id.ll_all_comment);
        return view;
    }

    /**
     * 商铺信息各种事件
     */
    private void initHeadViewEvent() {
        rl_shop_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showMapSelView(ShopDetailActivity.this, mLatLng);
            }
        });
        rl_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callShop();
            }
        });
        ll_all_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity(ShopDetailActivity.this, ShopCommentListActivity.class, PARAMS_SHOP_ID, shopId);
            }
        });

        mRl_technician.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocalActivity((Activity) mContext, ShopTechnicianActivity.class, PARAMS_SHOPID, shopId);
            }
        });
    }

    /**
     * 初始化商铺信息
     */
    private void initHeadViewData() {
        double lat = Double.valueOf(shopDetailEntity.getData().getLatitude());
        double lon = Double.valueOf(shopDetailEntity.getData().getLongitude());
        mLatLng = new LatLng(lat, lon);
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(mLatLng, 15, 0, 0)));
        tv_address.setText(shopDetailEntity.getData().getAddress());
        tv_shop_name.setText(shopDetailEntity.getData().getTitle());
        MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)).position(mLatLng)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_gps)).draggable(true);
        aMap.addMarker(markerOption);
        rb_start.setRating(shopDetailEntity.getData().getStatistic().getScore());
        String commentCount = String.format(getText(R.string.text_shop_comment_count).toString(),
                shopDetailEntity.getData().getStatistic().getComment());
        tv_count.setText(commentCount);
        String price = String.format(mContext.getText(R.string.text_price).toString(),
                shopDetailEntity.getData().getConsumption());
        tv_avg_price.setText(price);
        String commentNum = String.format(mContext.getText(R.string.text_shop_comment).toString(),
                shopDetailEntity.getData().getStatistic().getComment());
        tv_comment_count.setText(commentNum);

        String shopContent;
        if (null != shopDetailEntity.getData().getContent()) {
            shopContent = shopDetailEntity.getData().getContent().getContent();
        } else {
            shopContent = getText(R.string.text_shop_services_empty).toString();
        }

        tv_shop_detail.setText(shopContent);

        mTv_gril.setText(shopDetailEntity.getData().getGirls());

        tv_right_img_btn.setVisibility(View.VISIBLE);
        if (shopDetailEntity.getData().getIs_fav().equals(STATUS_TRUE)) {
            tv_right_img_btn.setSelected(true);
        }

        if (shopDetailEntity.getData().getHongbao().equals("1")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    iv_hongbao.setVisibility(View.VISIBLE);
                    Glide.with(mContext).load(R.mipmap.gif_hongbao_btn)
                            .asGif().into(iv_hongbao);
                }
            });
        }

        showBannerData();
        showManagerInfo();
    }

    /**
     * 经理列表
     */
    private void showManagerInfo() {
        btn_apply_manager.setVisibility(View.GONE);
        List<ShopDetailEntity.Managers> managerses = shopDetailEntity.getData().getManagers();
        if (null != managerses && managerses.size() > 0) {
            ll_manager.setVisibility(View.VISIBLE);
            initManagersAdapter();
        } else {
            ll_manager.setVisibility(View.GONE);
        }
    }

    /**
     * 经理列表
     */
    private void initManagersAdapter() {
        rv_manager.setLayoutManager(new MyLinearLayoutManager(this));
        ShopManagersAdapter shopManagersAdapter = new ShopManagersAdapter();
        shopManagersAdapter.setNewData(shopDetailEntity.getData().getManagers());
        rv_manager.setAdapter(shopManagersAdapter);
        shopManagersAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                ShopDetailEntity.Managers managers = (ShopDetailEntity.Managers) adapter.getData().get(position);

                switch (view.getId()) {
                    case R.id.ll_root:
                        startLocalActivity(ShopDetailActivity.this, ReservationShopActivity.class,
                                PARAMS_MANAGE_INFO, managers);
                        break;
                }
            }
        });
    }

    private boolean validPhone() {
        String phone = shopDetailEntity.getData().getPhone();
        phones = phone.split(" ");

        if (phone.trim().length() < 5)
            return false;

        if (phones.length > 1) {
            if (!CommonUtils.checkTelephone(phones[0]) && !CommonUtils.checkTelephone(phones[1])) {
                return false;
            }
        } else if (!CommonUtils.checkTelephone(phone)) {
            return false;
        }

        return true;
    }

    HashMap<String, String> map = new HashMap<String, String>();

    /**
     * 拨打电话
     */
    private void callShop() {
        if (!validPhone()) {
            ShowToast.showShortToast(getString(R.string.text_cantact_empty));
            return;
        }
        BottomSelectionPopup bottomSelectionPopup = new BottomSelectionPopup(this);
        bottomSelectionPopup.setTx_title(getString(R.string.text_call_phone));
        for (int i = 0; i < phones.length; i++) {
            if (CommonUtils.checkTelephone(phones[i].trim())) {
                if (i == 0) {
                    bottomSelectionPopup.setTx_1Text(phones[0]);
                } else {
                    bottomSelectionPopup.setTx_2Text(phones[1]);
                }
            }
        }
        bottomSelectionPopup.setOnClickItemListener(new BottomSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        map.put("shopName", shopDetailEntity.getData().getTitle());
                        MobclickAgent.onEvent(mContext, "call_shop_event", map);
                        CommonUtils.call(mContext, phones[0]);
                        break;
                    case R.id.ll_2:
                        map.put("shopName", shopDetailEntity.getData().getTitle());
                        MobclickAgent.onEvent(mContext, "call_shop_event", map);
                        CommonUtils.call(mContext, phones[1]);
                        break;
                }
            }
        });
        bottomSelectionPopup.showPopupWindow();
    }

    /**
     * 初始化banner数据
     */
    public void showBannerData() {
        List<String> images = shopDetailEntity.getData().getImages();
        if (images == null || images.size() < 0) {
            rl_convenientBanner.setVisibility(View.GONE);
            return;
        }
        convenientBanner.setPages(new CBViewHolderCreator<LocalImageHolderView>() {
            @Override
            public LocalImageHolderView createHolder() {
                return new LocalImageHolderView();
            }
        }, images)
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                .setOnItemClickListener(this);
        if (null == images || images.size() <= 1) {
            convenientBanner.setCanLoop(false);
        } else {
            convenientBanner.setCanLoop(true);
        }
    }


    @Override
    public void onItemClick(int position) {

    }

    @Override
    public void onResume() {
        super.onResume();
        convenientBanner.startTurning(3000);
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        convenientBanner.stopTurning();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
}
